package guestbook;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

import java.io.IOException;
import java.util.Date;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TiktolkServlet extends HttpServlet {
    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public void doPost(HttpServletRequest req, HttpServletResponse resp)
                throws IOException {
        UserService userService = UserServiceFactory.getUserService();
        User user = userService.getCurrentUser();

        // We have one entity group per Sector with all tiktolks residing
        // in the same entity group as the Sector to which they belong.
        // This lets us run a transactional ancestor query to retrieve all
        // tiktolks for a given Sector.  However, the write rate to each
        // Sector should be limited to ~1/second.
        String sector = req.getParameter("sector");
        Key sectorKey = KeyFactory.createKey("Sector", sector);
        String tiktolkName = req.getParameter("tiktolkName");
        Date date = new Date();
        Entity tiktolk = new Entity("tiktolk", sectorKey);
        tiktolk.setProperty("user", user);
        tiktolk.setProperty("date", date);
        tiktolk.setProperty("tiktolkName", tiktolkName);

        DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
        datastore.put(tiktolk);

        resp.sendRedirect("/tiktolk.jsp?tiktolkName=" + tiktolkName);
    }
}